//
//  XGL_CommentInputViewController.swift
//  XGamesLive
//
//  Created by ios on 2024/5/23.
//

import UIKit
import IQKeyboardManagerSwift

class XGL_CommentInputViewController: UIViewController {
    lazy var backView: UIView = {
        let view = UIView()
        view.backgroundColor = UIColor.black.withAlphaComponent(0.1)
        let tapGes = UITapGestureRecognizer(target: self, action: #selector(self.backTouchAction))
        tapGes.delegate = self
        view.addGestureRecognizer(tapGes)
        return view
    }()
    lazy var inputBar = XGL_CommentInputBar()
    lazy var giftPickerView = XGL_GiftListBarView()
    
    var touchDismissKeyboard: Bool = false{
        didSet{
            self.backView.isHidden = true
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.backView.isHidden = true
        self.view.addSubview(self.backView)
        self.view.addSubview(self.inputBar)
        self.backView.snp.makeConstraints { make in
            make.width.centerX.top.equalToSuperview()
            make.bottom.equalTo(self.inputBar.snp.top)
        }
        self.inputBar.snp.makeConstraints { make in
            make.width.centerX.equalToSuperview()
            make.bottom.equalToSuperview()
        }
        self.inputBar.giftItem.addTarget(self, action: #selector(self.giftItemAction), for: .touchUpInside)
        self.inputBar.sendItem.addTarget(self, action: #selector(self.sendItemAction), for: .touchUpInside)
        self.getCoinDataRequest()
        self.getGiftDatasRequest()
    }
    
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow(notification:)), name: UIResponder.keyboardWillShowNotification, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide(notification:)), name: UIResponder.keyboardWillHideNotification, object: nil)
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        IQKeyboardManager.shared.enable = false
        IQKeyboardManager.shared.enableAutoToolbar = false
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        IQKeyboardManager.shared.enable = true
        IQKeyboardManager.shared.enableAutoToolbar = true
    }
    
    override func viewDidDisappear(_ animated: Bool) {
        super.viewDidDisappear(animated)
        NotificationCenter.default.removeObserver(self)
    }
    
    open func sendComment(commentText: String){
        
    }
    open func sendGift(giftData: GiftData){
        
    }
}

extension XGL_CommentInputViewController{
    func selectGiftItem(){
        if self.inputBar.inputTextView.isFirstResponder{
            self.inputBar.inputTextView.resignFirstResponder()
        }
        self.view.addSubview(self.giftPickerView)
        self.giftPickerView.snp.makeConstraints { make in
            make.edges.equalToSuperview()
        }
        self.giftPickerView.showGiftPickerView { selectGift in
            self.sendGift(giftData: selectGift)
        }
    }
    
}

extension XGL_CommentInputViewController{
    private func getCoinDataRequest(){
        PanRequestManager<XGL_RequestBaseResponse<CoinData>,XGL_CustomRequestError>().request(XGLPersonalRequestAPI(requestAPI: .SurplusCoin)) { result in
            switch result{
            case .success(let response):
                if let data = response.resultData {
                    self.giftPickerView.coin = NSInteger(data.amount)
                }
                break
            default:
                break
            }
        }
    }
    private func getGiftDatasRequest(){
        PanRequestManager<XGL_RequestBaseResponse<PageModel<GiftData>>,XGL_CustomRequestError>().request(CustomRequestAPI(requestAPI: .Gifts)) { result in
            switch result{
            case .success(let response):
                if let data = response.resultData {
                    self.giftPickerView.giftSource = data.data
                }
                break
            default:
                break
            }
        }
    }
}

extension XGL_CommentInputViewController{
    
    @objc private func giftItemAction(){
        self.selectGiftItem()
    }
    @objc private func sendItemAction(){
        guard let comment = self.inputBar.inputTextView.text,comment.isEmpty == false else { return  }
        self.inputBar.inputTextView.text = ""
        self.inputBar.inputTextView.resignFirstResponder()
        self.sendComment(commentText: comment)
    }
    
    @objc private func keyboardWillShow(notification: Notification) {
        self.view.bringSubviewToFront(self.inputBar)
        guard let userInfo = notification.userInfo else {
            return
        }
        self.backView.isHidden = !self.touchDismissKeyboard

        if IQKeyboardManager.shared.enable == false{
            let animationDuration: TimeInterval = (userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
            let endFrame = (userInfo[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue).cgRectValue

            UIView.animate(withDuration: animationDuration, animations: {
                self.inputBar.transform = CGAffineTransform(translationX: 0, y: -(endFrame.height - BottomHeight))
            }, completion: nil)
        }
        
    }
    
    @objc private func keyboardWillHide(notification: Notification) {

        guard let userInfo = notification.userInfo else {
            return
        }
        self.view.layoutIfNeeded()
        self.backView.isHidden = true
        let animationDuration: TimeInterval = (userInfo[UIResponder.keyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue

        UIView.animate(withDuration: animationDuration, animations: {
            self.inputBar.transform = .identity
        }, completion: nil)
    }
    
    @objc private func backTouchAction(){
        self.inputBar.inputTextView.resignFirstResponder()
        self.view.endEditing(true)
    }
}

extension XGL_CommentInputViewController: UIGestureRecognizerDelegate{
    func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool {
        let touchPoint = touch.location(in: self.view)
        self.inputBar.layoutIfNeeded()
        if self.inputBar.frame.contains(touchPoint){
            return false
        }
        
        return true
    }
}
